<template>
  <div class="app-container">
    <!-- 登录信息查询表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="登录地址" prop="ipaddr">
        <el-input
          v-model="queryParams.ipaddr"
          placeholder="请输入登录地址"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="登录状态" clearable style="width: 240px">
          <el-option v-for="item in commonStatus" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
        </el-select>
      </el-form-item>
    </el-form>
    <!-- 查询操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-button type="primary" @click="handleQuery">搜索</el-button>
      <el-button @click="resetQuery">重置</el-button>
      <el-col :span="1.5">
        <el-button type="danger" plain :disabled="!ids.length" @click="handleDelete" v-p="['monitor:logininfor:remove']">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain @click="handleClean" v-p="['monitor:logininfor:remove']">清空</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :disabled="selectName.length === 0 || selectName.length > 1"
          @click="handleUnlock"
          v-p="['monitor:logininfor:unlock']"
        >
          解锁
        </el-button>
      </el-col>
    </el-row>
    <!-- 登录信息表格 -->
    <el-table ref="tables" v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="访问编号" align="center" prop="infoId" />
      <el-table-column label="用户名称" align="center" prop="userName" :show-overflow-tooltip="true" sortable />
      <el-table-column label="登录地址" align="center" prop="ipaddr" width="130" :show-overflow-tooltip="true" />
      <el-table-column label="登录地点" align="center" prop="loginLocation" :show-overflow-tooltip="true" />
      <el-table-column label="浏览器" align="center" prop="browser" :show-overflow-tooltip="true" />
      <el-table-column label="操作系统" align="center" prop="os" />
      <el-table-column label="登录状态" align="center" prop="status">
        <template v-slot="scope">
          <el-tag v-if="scope.row.status === '0'" type="">成功</el-tag>
          <el-tag v-else type="danger">失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作信息" align="center" prop="msg" :show-overflow-tooltip="true" />
      <el-table-column label="登录日期" align="center" prop="loginTime" sortable width="180" />
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @update:page="handlePageChange"
      @update:limit="handlePageSizeChange"
    />
  </div>
</template>

<script setup lang="ts">
import type { DictData, LoginData } from "@/typings";
import type { FormInstance } from "element-plus";
import { onMounted, ref } from "vue";
import { cleanLoginInfoApi, delLoginInfoApi, getLoginInfoListApi, unlockLoginInfoApi, getDictDataTypeApi } from "@/api";
import { ElMessage, ElMessageBox } from "element-plus";
import Pagination from "@/components/pagination/Pagination.vue";

// 状态管理
const ids = ref<number[]>([]);
const selectName = ref<string[]>([]);
const loading = ref(false);
const list = ref<LoginData[]>([]);
const total = ref(0);
const commonStatus = ref<DictData[]>([]);
const queryForm = ref<FormInstance>();
const queryParams = ref({
  ipaddr: undefined,
  userName: undefined,
  status: undefined,
  pageNum: 1,
  pageSize: 10
});

// 查询登录信息
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getLoginInfoList();
};

// 重置查询条件
const resetQuery = () => {
  queryForm.value?.resetFields();
  getLoginInfoList();
};

// 删除选中的登录日志
const handleDelete = () => {
  ElMessageBox.confirm("确定删除所勾选的登录日志数据吗？删除之后数据将无法恢复", "系统提示", {
    type: "warning"
  }).then(async () => {
    try {
      const res = await delLoginInfoApi(ids.value.join(","));
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getLoginInfoList();
        return;
      }
      ElMessage.error(res.message);
    } catch (error) {
      console.error("删除操作日志失败");
    }
  });
};

// 清空所有登录日志
const handleClean = async () => {
  try {
    const res = await cleanLoginInfoApi();
    if (res.code === 200) {
      ElMessage.success("清空成功");
      getLoginInfoList();
      return;
    }
    ElMessage.error(res.message);
  } catch (error) {
    console.error("清空操作日志失败");
  }
};

// 解锁选中的用户数据
const handleUnlock = () => {
  ElMessageBox.confirm(`是否确认解锁用户${selectName.value}数据项?`, "系统提示", {
    type: "warning"
  })
    .then(async () => {
      try {
        const res = await unlockLoginInfoApi(selectName.value.join(","));
        if (res.code === 200) {
          ElMessage.success("解锁成功");
          getLoginInfoList();
          return;
        }
        ElMessage.error(res.message);
      } catch (error) {
        console.error("解锁操作日志失败");
      }
    })
    .catch(() => {});
};

// 处理表格选择变化
const handleSelectionChange = (data: LoginData[]) => {
  ids.value = data.map((item: LoginData) => item.infoId);
  selectName.value = data.map((item: LoginData) => item.userName);
};

// 处理页码变化
const handlePageChange = (page: number) => {
  queryParams.value.pageNum = page;
  getLoginInfoList();
};

// 处理每页条数变化
const handlePageSizeChange = (size: number) => {
  queryParams.value.pageSize = size;
  getLoginInfoList();
};

// 获取登录信息列表
const getLoginInfoList = async () => {
  try {
    loading.value = true;
    const res = await getLoginInfoListApi(queryParams.value);
    if (res.code === 200) {
      list.value = res.data;
      total.value = res.total as number;
      return;
    }
    ElMessage.error(res.message);
  } catch (error) {
    console.error("获取登录日志列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取字典数据类型
const getDictDataType = async () => {
  try {
    const response = await getDictDataTypeApi("sys_common_status");
    if (response.code === 200) {
      commonStatus.value = response.data;
      return;
    }
    ElMessage.error(response.message);
  } catch (error) {
    console.error("获取字典数据类型失败");
  }
};

// 组件挂载后执行的方法
onMounted(() => {
  getLoginInfoList();
  getDictDataType();
});
</script>
